#include "qwalkmanobject.h"

#include <QNetworkRequest>
#include <QJsonDocument>
#include <QJsonParseError>
#include <QJsonObject>
#include <QApplication>
#include <QDir>
#include <QDebug>

QWalkmanObject::QWalkmanObject(QObject *parent, bool isAutoPlay) :
    QObject(parent),m_medialplayer(nullptr)
{
    m_isAutoDownload = false;
    m_localFile = nullptr;
    m_strFilePath = qApp->applicationDirPath() + "/musics/";

    m_networkManager = new QNetworkAccessManager(this);
    if (isAutoPlay) {
        m_medialplayer = new QMediaPlayer(this);
        connect(m_medialplayer, SIGNAL(durationChanged(qint64)), this, SLOT(durationChanged(qint64)));
        connect(m_medialplayer, SIGNAL(positionChanged(qint64)), this, SLOT(positionChanged(qint64)));
        connect(m_medialplayer, SIGNAL(error(QMediaPlayer::Error)), this, SLOT(error(QMediaPlayer::Error)));
    }

    checkDir(m_strFilePath);
}

QWalkmanObject::~QWalkmanObject()
{

}

void QWalkmanObject::startMusic(const QString &_musicType)
{
    QNetworkRequest request; 
    QSslConfiguration config;
    QSslConfiguration conf = request.sslConfiguration();
    conf.setPeerVerifyMode(QSslSocket::VerifyNone);
    conf.setProtocol(QSsl::TlsV1SslV3);
    request.setSslConfiguration(conf);

    request.setUrl(QUrl(QString("https://api.uomg.com/api/rand.music?sort=%1&format=json").arg(_musicType)));
    QNetworkReply *reply = m_networkManager->get(request);
    connect(reply, SIGNAL(finished()), this, SLOT(sltHttpFinished()));
}

void QWalkmanObject::playAndPause()
{
    if (nullptr == m_medialplayer) return;
    if (m_medialplayer->state() == QMediaPlayer::PlayingState) {
        m_medialplayer->pause();
    } else if (m_medialplayer->state() == QMediaPlayer::PausedState) {
        m_medialplayer->play();
    }
}

void QWalkmanObject::dowloadCurrent()
{
    if (m_url.isEmpty()) return;
    downloadFile(m_url);
}

void QWalkmanObject::checkDir(const QString &_path)
{
    QDir dir(_path);
    if (!dir.exists()) {
        dir.mkpath(_path);
    }
}

void QWalkmanObject::parseJsonData(const QByteArray &_byData)
{
    QJsonParseError jsonErr;
    QJsonDocument document = QJsonDocument::fromJson(_byData, &jsonErr);
    if (!document.isNull() && (jsonErr.error == QJsonParseError::NoError)) {
        QJsonObject jsonObj = document.object();
        int code = jsonObj.value("code").toInt();
        if (code == 1) {
            QJsonObject jsonData = jsonObj.value("data").toObject();
            QString artist = jsonData.value("artistsname").toString();
            QString strName = jsonData.value("name").toString();
            QString strPic = jsonData.value("picurl").toString();
            m_url = QUrl(jsonData.value("url").toString());
            m_strFileName = artist + " - " + strName + ".mp3";

            if (nullptr == m_medialplayer) {
                if (m_medialplayer->state() == QMediaPlayer::PlayingState) {
                    m_medialplayer->stop();
                }
                m_medialplayer->setMedia(m_url);
                m_medialplayer->play();
            }
            else {
                emit playSong(m_url);
                if (nullptr == m_localFile) {
                    m_localFile = new QFile(this);
                }
                m_localFile->setFileName(m_strFilePath + "artist.jpg");
                if (m_localFile->open(QIODevice::ReadWrite))
                {
                    downloadFile(strPic);
                }
            }

            emit songChanged(artist + ":" + strName);
            if (m_isAutoDownload) {
                downloadFile(m_url);
            }
        }
    }
}

void QWalkmanObject::downloadFile(const QUrl &url)
{
    QNetworkRequest request;
    request.setUrl(url);
    m_networkDownlad = m_networkManager->get(request);
    connect(m_networkDownlad, SIGNAL(finished()), this, SLOT(sltHttpFinished()));
    connect(m_networkDownlad, SIGNAL(readyRead()), this, SLOT(sltHttpRead()));
}

void QWalkmanObject::sltHttpRead()
{
    if (m_localFile && m_localFile->isOpen()) {
        m_localFile->write(m_networkDownlad->readAll());
    }
}

void QWalkmanObject::sltHttpFinished()
{
    QNetworkReply *_reply = qobject_cast<QNetworkReply *>(this->sender());
    if (_reply->error() == QNetworkReply::NoError) {
        if (m_networkDownlad == _reply) {
            if (m_localFile && m_localFile->isOpen()) {
                QFileInfo fileinfo(m_localFile->fileName());
                emit downloadFinished(fileinfo.fileName());
                m_localFile->flush();
                m_localFile->close();
                if (m_localFile->size() == 0) {
                    QFile::remove(m_localFile->fileName());
                }
                delete m_localFile;
                m_localFile = nullptr;
            }

            const QVariant redirectTarget = _reply->attribute(QNetworkRequest::RedirectionTargetAttribute);
            if (!redirectTarget.isNull()) {
                if (nullptr == m_localFile) {
                    m_localFile = new QFile(this);
                }
                m_localFile->setFileName(m_strFilePath + m_strFileName);
                if (m_localFile->open(QIODevice::ReadWrite))
                {
                    QString strUrl = redirectTarget.toUrl().toString();
                    downloadFile(strUrl);
                }
            }
        } else {
            parseJsonData(_reply->readAll());
        }
    }

    _reply->deleteLater();
    _reply = nullptr;
}

void QWalkmanObject::durationChanged(qint64 duration)
{
    m_duration = duration;
}

void QWalkmanObject::positionChanged(qint64 position)
{
    if (position >= m_duration){
        startMusic();
    }
}

void QWalkmanObject::error(QMediaPlayer::Error error)
{
    if (QMediaPlayer::NoError != error) {
        startMusic();
    }
}
